package com.link2room.rodimus.service.impl;

import com.link2room.common.dao.ICommonDao;
import com.link2room.common.exception.SysException;
import com.link2room.common.service.ICommonService;
import com.link2room.rodimus.entity.MallOrderBase;
import com.link2room.rodimus.entity.MallOrderPrice;
import com.link2room.rodimus.service.IMallOrderService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

import static com.link2room.enums.exception.RodimusSysExceptionEnum.GENERATE_NEW_ORDERNO_ERROR;


/**
 * Created by LN on 2017/9/6.9:48
 */
@Component("mallOrderService")
public class MallOrderServiceImpl implements IMallOrderService {
    @Resource
    private ICommonDao commonDao;
    @Resource
    private ICommonService commonService;
    @Autowired
    private RedisLockRegistry mallOrderNoLock;

    private final static String MALLORDER = "MALLORDER";
    @Override
    @Transactional
    public void saveNewMallOrder(MallOrderBase orderBase, List<MallOrderPrice> orderPrices) throws Exception {
        if(orderBase != null){
            commonDao.save(orderBase);
        }
        if(CollectionUtils.isNotEmpty(orderPrices)){
            commonDao.saveList(orderPrices);
        }
    }

    @Override
    public String generateNewOrderNo() throws Exception {
        Lock lock = mallOrderNoLock.obtain(MALLORDER);
        if(lock.tryLock(5, TimeUnit.SECONDS)){
            try {
                //0 初始化
                List<MallOrderPrice> mallOrderPrices = new ArrayList<>();
                List params = new ArrayList<>();
                params.add(MALLORDER);
                return commonService.findOneFieldByProcedure("create_No", params);
            }finally {
                lock.unlock();
            }
        }else {
            throw new SysException(GENERATE_NEW_ORDERNO_ERROR,"当前下单人数太多,稍后重试");
        }
    }
}
